//
//  CZNetworkTool.swift
//  swiftweibo1.0
//
//  Created by 许建安 on 15/11/26.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import AFNetworking //用来请求网络的框架

//网络单例
class CZNetworkTool: AFHTTPSessionManager {
    //单例
    static let sharedInstance: CZNetworkTool = { //一个类方法
        //baseURL,基础微博网站，用于后面各种拼接
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tool = CZNetworkTool(baseURL: baseURL)//把baseURL转换格式
        
        //添加响应的序列化器
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    ///MARK: - Oauth授权
    ///申请应用时分配的appKey
    private let client_id = "2850925374"
    
    ///申请应用时分配的appSecret
    private let client_secret = "453631bf39ed7b243a6f17babdb78f5d"
    
    ///授权回调地址
    let redirect_uri = "http://www.baidu.com/"
    
    //返回授权界面的URL地址
    func oauthURL() -> NSURL {
        //GET的方式拼接登录界面请求地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    //MARK: - 网络工具类加载AccessToken,只负责加载数据，让别人来处理数据（通过闭包）
    func loadAccessToken(code: String,finished: (result: [String: AnyObject]?,error:NSError?) -> ()) {
        
        //url地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let parameters = [
            "client_id":client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code" : code,
            "redirect_uri": redirect_uri
        ]
        //发送POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            finished(result: result as?[String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
    }
}
